<template>
  <a-card :bordered="false" style="max-width: 600px; margin: 0 auto">
    <h2>发布新帖子</h2>
    <a-form
      :model="postForm"
      label-align="left"
      @submit="handleSubmit"
      :style="{ width: '100%' }"
    >
      <a-form-item label="帖子标题" required>
        <a-input v-model="postForm.title" placeholder="请输入帖子标题" />
      </a-form-item>
      <a-form-item label="帖子内容" required>
        <a-textarea
          v-model="postForm.content"
          placeholder="请输入帖子内容"
          rows="5"
        />
      </a-form-item>
      <a-form-item label="标签">
        <a-input v-model="postForm.tags" placeholder="请输入标签，用逗号分隔" />
      </a-form-item>
      <a-form-item>
        <a-button
          type="primary"
          html-type="submit"
          :loading="loading"
          style="width: 100%"
        >
          发布帖子
        </a-button>
      </a-form-item>
    </a-form>
  </a-card>
</template>

<script setup lang="ts">
import { ref } from "vue";
import { useRouter } from "vue-router";
import { addPostUsingPost } from "@/api/postController";
import message from "@arco-design/web-vue/es/message";

const router = useRouter();
const loading = ref(false);
const postForm = ref({
  title: "",
  content: "",
  tags: "",
});

// 发布帖子
const handleSubmit = async () => {
  loading.value = true;
  try {
    const res = await addPostUsingPost({
      title: postForm.value.title,
      content: postForm.value.content,
      tags: postForm.value.tags.split(",").map((tag) => tag.trim()),
    });
    if (res.data.code === 0) {
      message.success("帖子发布成功");
      router.push("/posts"); // 发布成功后跳转到帖子广场
    } else {
      message.error("发布失败：" + res.data.message);
    }
  } catch (error) {
    message.error("发布失败，请稍后重试");
  } finally {
    loading.value = false;
  }
};
</script>

<style scoped>
/* 样式可以根据需要调整 */
</style>
